package top.rainf.support;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 星环
 * @date 2023/6/5 16:34:10
 * @description
 */
public class StringMatcher {
    public static String[] extractMatches(String content, String regex) {
        //将这个正则表达式字符串转换为对象
        Pattern pattern = Pattern.compile(regex);
        //获得匹配类对象，组合正则表达式和要匹配的内容
        Matcher matcher = pattern.matcher(content);

        // 使用StringBuilder来动态构建匹配到的字符串数组
        List<String> matches = new LinkedList<>();

        while (matcher.find()) {
            //每匹配一个
            matches.add(matcher.group());

            System.out.println(matches);
            //存起来
        }
        return matches.toArray(new String[0]);

    }

    public static void main(String[] args) {
        String content = "这是一段 @ww@what @匹配的测试 @代码";
        String regex = "(?:@)\\w+";

        String[] extractedStrings = extractMatches(content, regex);

        // 输出匹配到的字符串数组
        for (String extractedString : extractedStrings) {
            System.out.println(extractedString);
        }
    }
}
